package com.comp6231.frontend;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * 
 * This is the class which extents thread and implements
 * the run method.
 * 
 * This thread is created to receive messages from Coordinator
 * This class can receive two types of messages:
 * 1. Leader Coordinators information
 * 2. Reply for clietn request
 *
 * @author sknarula (narula.sk@gmail.com)
 * @since November 2013
 * 
 */
import com.comp6231.common.Request;

public class RegisterLeader extends Thread {

	@SuppressWarnings("unused")
	private String myHostName;
	private int myControlUDPPort;

	public RegisterLeader(String hostName, String controlUDPPort) {
		this.myHostName = hostName;
		this.myControlUDPPort = new Integer(controlUDPPort);
	}

	/**
	 * This thread will listen to the control UDP port for the (new) leaders to
	 * register themselves to Front End
	 * 
	 */
	@Override
	public void run() {
		DatagramSocket socket = null;
		try {
			socket = new DatagramSocket(myControlUDPPort);
			byte[] buffer = new byte[1000];
			System.out.println("UDP server for control channel @Front End"
					+ " is running on: " + myControlUDPPort);
			while (true) {
				DatagramPacket request = new DatagramPacket(buffer,
						buffer.length);
				socket.receive(request);
				Request data = new Request(request).parsePacket();
				String message = "";

				if (data.getOperation().equalsIgnoreCase("Register")) {
					FrontEndInitiator.leaderHostName = data.getHostName();
					FrontEndInitiator.leaderUDPPort = data.getUDPPort();
					message = "Success";
					System.out.println("\nThe leader is: "
							+ data.getEntityName());
					/*
					 * if the system is started first time and the
					 * hasLeaderAddress is set to false open the CORBA interface
					 * for client calls
					 */
					if (!FrontEndInitiator.hasLeaderAddress) {
						(new ClientInterface()).start();
						FrontEndInitiator.hasLeaderAddress = true;
					}
				}

				DatagramPacket reply = new DatagramPacket(message.toLowerCase()
						.getBytes(), message.length(), request.getAddress(),
						request.getPort());
				socket.send(reply);
			}
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (socket != null)
				socket.close();
		}
	}

}
